package com.indsvr.utils;

import com.google.gson.Gson;
import lombok.Setter;
import okhttp3.*;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.function.BiConsumer;

public class XunleiOkHttpUtils {

    private static OkHttpClient okHttpClient;

    @Setter
    private String token;
    @Setter
    private String deviceSpace;
    @Setter
    private String deviceId;

    @Setter
    private String baseUrl;


    @Deprecated
    public String getBodyExecute(String url, Object formBody) throws IOException {

        if (okHttpClient == null) {
            try {
                TrustManager[] trustAllCerts = buildTrustManagers();
                final SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

                final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

                okHttpClient = new OkHttpClient.Builder()
                        .followRedirects(false)
                        .sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0])
                        .hostnameVerifier((hostname, session) -> true)
                        .build();
            }catch (Exception ignored){}
        }

        Request.Builder builder = new Request.Builder().url(url);
        if (token != null) {
            builder.header("pan-auth", token);
        }

        if (formBody != null) {
            MediaType JSON = MediaType.parse("application/json;charset=utf-8");
            RequestBody requestBody = RequestBody.create(new Gson().toJson(formBody), JSON);
            builder.post(requestBody);
        }

        builder.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:85.0) Gecko/20100101 Firefox/85.0");
        Request build = builder.build();
        Response execute = okHttpClient.newCall(build).execute();
        ResponseBody body = execute.body();
        String string = body.string();
        body.close();
        return string;
    }


    public String execute(String url, HashMap<String, String> params, Object body) throws IOException {

        if (params == null) {
            params = new HashMap<>();
        }

        //填充必要参数
        if (deviceId != null) {
            params.put("space", deviceId);
        }
        if (deviceSpace != null) {
            params.put("device_space", deviceSpace);
        }
        if (token != null) {
            params.put("pan_auth", token);
        }

        int i = 0;
        StringBuilder urlBuilder = new StringBuilder(url);
        for (String s : params.keySet()) {
            if (i == 0) {
                urlBuilder.append("?");
            } else {
                urlBuilder.append("&");
            }
            String s1 = params.get(s);
            urlBuilder.append(s).append("=").append(URLEncoder.encode(s1, StandardCharsets.UTF_8));
            i = i + 1;
        }
        url = urlBuilder.toString();

        if (okHttpClient == null) {
            okHttpClient = new OkHttpClient.Builder()
                    .followRedirects(false)
                    .build();
        }

        Request.Builder builder = new Request.Builder().url(baseUrl + url);
        if (token != null) {
            builder.header("pan-auth", token);
        }

        if (body != null) {
            MediaType JSON = MediaType.parse("application/json;charset=utf-8");
            RequestBody requestBody = RequestBody.create(new Gson().toJson(body), JSON);
            builder.post(requestBody);
        }

        builder.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:85.0) Gecko/20100101 Firefox/85.0");
        Request build = builder.build();
        Response execute = okHttpClient.newCall(build).execute();
        ResponseBody responseBody = execute.body();
        String string = responseBody.string();
        responseBody.close();
        return string;
    }


    private static TrustManager[] buildTrustManagers() {
        return new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                }
        };
    }
}